/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;

//import sc_lib.ClientInfo;
/**
 *
 * @author Vuong
 */
public class ClientXMLServerInfo extends XML {
    public static boolean add(ServerInfo newInfo) throws IOException, JDOMException {
        try
        {
            Document myDocument = readDocument(Constants.SERVER_CONFIG);
            Element clientInfos = myDocument.getRootElement();

            clientInfos.addContent(createClientInfoTags(newInfo));

            outputDocumentToFile(myDocument, Constants.SERVER_CONFIG);

            return true;
        }
        catch(Exception ex)
        {
            return false;
        }
    }

    private static Element createClientInfoTags(ServerInfo defaultServerInfo) {
        Element serInfo = new Element("ServerInfo");
        serInfo.addContent(new Element("ServerIP").addContent(defaultServerInfo.GetIP()));
        serInfo.addContent(new Element("ServerPort").addContent(defaultServerInfo.GetPort()));
        return serInfo;
    }

    public static ServerInfo GetInfo() throws IOException, JDOMException {
        try
        {
            Document myDocument = readDocument(Constants.SERVER_CONFIG);
            Element clientInfos = myDocument.getRootElement();

            Element serverInfo = clientInfos.getChild("ServerInfo");

            if (serverInfo != null) {
                ServerInfo info = new ServerInfo();
                info.Set(serverInfo.getChildText("ServerIP"), serverInfo.getChildText("ServerPort"));
                return info;
            } else {
                //System.out.println("Can not find the infos of " + clientInfo.getChildText("ID") + "!");
            }

            return null;
        }
        catch(Exception ex)
        {
            return null;
        }
    }
    
    public static boolean update(ServerInfo updatedInfo) throws IOException, JDOMException {
        try
        {
            Document myDocument = readDocument(Constants.SERVER_CONFIG);

            if (removeChildElement(myDocument, "ServerInfo")) {
                Element serverInfos = myDocument.getRootElement();
                serverInfos.addContent(createClientInfoTags(updatedInfo));

                outputDocumentToFile(myDocument, Constants.SERVER_CONFIG);

                return true;
            }
            return false;
        }
        catch(Exception ex)
        {
            return false;
        }
    }
}
